import random

import redis
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
import logging
from celery_tasks.sms.tasks import send_sms_code
# 创建
from meiduo_mall.libs.yuntongxun.sms import CCP
from . import constants


class SMSCodeView(APIView):
    """发送短信验证码
    传入参数　mobile
    流程: 1 首先连接到redis数据库
    　　　2　其次是从数据库查找mobile中是否有已经存在(存在说明，验证码已经发了)
    　　　3　生成６为的短信验证码
    　　　4 采用第三方API，发送短信至相应的手机号码
    　　　5　利用pipeline，将手机号码和标志符号存入redis数据库
         6 返回相应的状态
    """

    def get(self, request, mobile):
        logger = logging.getLogger("django")
        redis_conn = get_redis_connection("verify")
        send_flag = redis_conn.get("send_msg_%s" % mobile)
        # print(mobile)
        if send_flag:
            return Response({"message": "操作过于频繁！"}, status=status.HTTP_400_BAD_REQUEST)
        sms_code = "%06d" % random.randint(0, 999999)
        try:
            send_sms_code.delay(mobile, sms_code)
        except Exception as e:
            logger.error("短信发送失败: %s" % e)
            return Response({"message": "发送短信失败！"}, status=status.HTTP_400_BAD_REQUEST)

        redis_pip = redis_conn.pipeline()
        redis_pip.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        redis_pip.setex("sms_%s_flag" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        redis_pip.execute()
        return Response({"message": "OK"}, status=status.HTTP_200_OK)

